﻿using System;
using System.Net.Sockets;
using System.Text;

namespace Pst_Backup_Agent
{
    internal class Client:IDisposable
    {
        private Socket _clientSocket;
        private string _serverAddress = string.Empty;
        private int _serverPort = 42000;
        private Utilities logger = new Utilities();

        internal Client(string serverAddress, int serverPort)
        {
            this._serverAddress = serverAddress;
            this._serverPort = serverPort;
        }

        internal void Connect()
        {
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            _clientSocket.ReceiveTimeout = 10000;
            _clientSocket.SendTimeout = 10000;
            _clientSocket.Connect(_serverAddress, _serverPort);
        }

        internal void SendMessage(string message)
        {
            byte[] endOfMessage = UnicodeEncoding.UTF8.GetBytes("?EndOfMessage?");

            if (_clientSocket.Connected)
            {
                byte[] messageToSend = UnicodeEncoding.UTF8.GetBytes(message);
                try
                {
                    _clientSocket.Send(messageToSend);
                    _clientSocket.Send(endOfMessage);
                }
                catch (SocketException socketEx)
                {
                    if (socketEx.SocketErrorCode == SocketError.ConnectionAborted)
                    {
                        _clientSocket = null;
                        this.Connect();
                        _clientSocket.Send(messageToSend);
                        _clientSocket.Send(endOfMessage);
                    }
                    else
                        throw;
                }
            }
            else
            {
                throw new SocketException((int)SocketError.NotConnected);
            }
        }

        internal void Disconnect()
        {
            _clientSocket.Close();
            _clientSocket = null;
        }

        void IDisposable.Dispose()
        {
            this.Disconnect();
        }
    }
}
